<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="省">
        <el-select v-model="searchForm.provinceId" placeholder="请选择省" clearable @change="handleProvinceChange">
          <el-option
            v-for="province in provinceOptions"
            :key="province.id"
            :label="province.name"
            :value="province.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="市">
        <el-select v-model="searchForm.cityId" placeholder="请选择市（请先选择省）" clearable @change="handleCityChange" :disabled="!searchForm.provinceId">
          <el-option
            v-for="city in cityOptions"
            :key="city.id"
            :label="city.name"
            :value="city.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="区/县">
        <el-select v-model="searchForm.districtId" placeholder="请选择区/县（请先选择市）" clearable :disabled="!searchForm.cityId">
          <el-option
            v-for="district in districtOptions"
            :key="district.id"
            :label="district.name"
            :value="district.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearchForm">重置</el-button>
        <el-button type="success" @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格区域 -->
    <el-table
      :data="tableData"
      border  style="width: 100%"
      @selection-change="handleSelectionChange"
      ref="table"
      v-loading="loading"
    >
      <el-table-column type="selection" width="33" align="center" />
      <el-table-column prop="provinceName" label="省" align="center" />
      <el-table-column prop="cityName" label="市" align="center" />
      <el-table-column prop="districtName" label="区/县" align="center" />
      <el-table-column prop="unitName" label="所属单位" align="center" />
      <el-table-column prop="department" label="所属部门" align="center" />
      <el-table-column prop="unitLogo" label="单位logo" align="center">
        <template #default="{ row }">
          <image-preview v-if="row.unitLogo" :src="row.unitLogo" alt="单位logo" style="width: 50px; height: 50px; object-fit: cover;" />
          <span v-else>无logo</span>
        </template>
      </el-table-column>
      <el-table-column prop="configValue" label="配置项" align="center">
        <template #default="{ row }">
          {{ getConfigDescription(row.configValue) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="loadUnitList"
    />

    <!-- 编辑弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" @close="handleDialogClose">
      <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="100px">
        <el-form-item label="省" prop="province">
          <el-select v-model="editForm.province" placeholder="请选择省" @change="handleEditProvinceChange">
            <el-option
              v-for="province in provinceOptions"
              :key="province.id"
              :label="province.name"
              :value="province.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-select v-model="editForm.city" placeholder="请选择市" @change="handleEditCityChange" :disabled="!editForm.province">
            <el-option
              v-for="city in editCityOptions"
              :key="city.id"
              :label="city.name"
              :value="city.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="区/县" prop="district">
          <el-select v-model="editForm.district" placeholder="请选择区/县" :disabled="!editForm.city">
            <el-option
              v-for="district in editDistrictOptions"
              :key="district.id"
              :label="district.name"
              :value="district.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属单位" prop="unitName">
          <el-input v-model="editForm.unitName" />
        </el-form-item>
        <el-form-item label="所属部门" prop="department">
          <el-input v-model="editForm.department" />
        </el-form-item>
        <el-form-item label="单位logo" prop="unitLogo">
          <el-input v-model="editForm.unitLogo" placeholder="请输入logo图片路径" />
        </el-form-item>
        <el-form-item label="配置项" prop="configValue">
          <el-select v-model="editForm.configValue" placeholder="请选择配置项">
            <el-option label="标题(0)" value="0" />
            <el-option label="LOGO(1)" value="1" />
            <el-option label="打印(2)" value="2" />
            <el-option label="首页(3)" value="3" />
            <el-option label="四川省追溯平台(4)" value="4" />
            <el-option label="大屏权限(5)" value="5" />
            <el-option label="合格证抬头(6)" value="6" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list,getRegulatorUnits, addRegulatorUnit, updateRegulatorUnit, deleteRegulatorUnit } from '@/api/regulator/region'
export default {
  data() {
    return {
      // 搜索表单 - 修改为使用ID
      searchForm: {
        provinceId: '',
        cityId: '',
        districtId: ''
      },
      // 省市区选项数据
      provinceOptions: [],
      cityOptions: [],
      districtOptions: [],
      // 表格数据和其他必要数据
      tableData: [],
      total: 0,
      loading: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 编辑对话框相关
      dialogVisible: false,
      dialogTitle: '',
      editForm: {
        id: undefined,
        province: '',
        city: '',
        district: '',
        unitName: '',
        department: '',
        unitLogo: '',
        configValue: ''
      },
      editRules: {
        province: [{ required: true, message: '请选择省', trigger: 'change' }],
        city: [{ required: true, message: '请选择市', trigger: 'change' }],
        district: [{ required: true, message: '请选择区/县', trigger: 'change' }],
        unitName: [{ required: true, message: '请输入所属单位', trigger: 'blur' }],
        department: [{ required: true, message: '请输入所属部门', trigger: 'blur' }],
        configValue: [{ required: true, message: '请选择配置项', trigger: 'change' }]
      },
      editCityOptions: [],
      editDistrictOptions: []
    }
  },

  created() {
    this.loadProvinceOptions()
    this.loadUnitList()
  },

  methods: {
    // 加载省份选项 - 修改为使用ID
    async loadProvinceOptions() {
      try {
        const response = await list({}) // 获取所有地区信息
        const regions = response.data

        // 提取唯一省份列表，使用ID和名称
        this.provinceOptions = [...new Map(regions.map(item => [item.provinceId, {
          id: item.provinceId,
          name: item.provinceName
        }])).values()]
      } catch (error) {
        console.error('获取省份列表失败:', error)
        this.$message.error('获取省份列表失败')
      }
    },

    // 省份选择变化时 - 修改为使用ID
    async handleProvinceChange(selectedProvinceId) {
      // 重置城市和区县选择
      this.searchForm.cityId = ''
      this.searchForm.districtId = ''
      this.cityOptions = []
      this.districtOptions = []

      if (!selectedProvinceId) return

      try {
        // 根据选中的省份ID获取城市列表
        const response = await list({provinceId: selectedProvinceId})
        const regions = response.data

        // 提取唯一城市列表，使用ID和名称
        this.cityOptions = [...new Map(regions.map(item => [item.cityId, {
          id: item.cityId,
          name: item.cityName
        }])).values()]
      } catch (error) {
        console.error('获取城市列表失败:', error)
        this.$message.error('获取城市列表失败')
      }
    },

    // 城市选择变化时 - 修改为使用ID
    async handleCityChange(selectedCityId) {
      // 重置区县选择
      this.searchForm.districtId = ''
      this.districtOptions = []

      if (!selectedCityId) return

      try {
        // 根据选中的城市ID获取区县列表
        const response = await list({
          provinceId: this.searchForm.provinceId,
          cityId: selectedCityId
        })
        const regions = response.data

        // 提取区县列表，使用ID和名称
        this.districtOptions = [...new Map(regions.map(item => [item.districtId, {
          id: item.districtId,
          name: item.districtName
        }])).values()]
      } catch (error) {
        console.error('获取区县列表失败:', error)
        this.$message.error('获取区县列表失败')
      }
    },

    // 查询按钮点击事件
    handleSearch() {
      this.queryParams.pageNum = 1
      this.loadUnitList()
    },

    // 重置搜索表单 - 修改为重置ID
    resetSearchForm() {
      this.searchForm = {
        provinceId: '',
        cityId: '',
        districtId: ''
      }
      this.cityOptions = []
      this.districtOptions = []
      this.handleSearch()
    },

    // 加载单位列表 - 修改为传递ID参数
    async loadUnitList() {
      this.loading = true
      try {
        const query = {
          ...this.queryParams,
          provinceId: this.searchForm.provinceId,
          cityId: this.searchForm.cityId,
          districtId: this.searchForm.districtId
        }

        const response = await getRegulatorUnits(query)
        this.tableData = response.rows
        this.total = response.total
      } catch (error) {
        console.error('获取单位列表失败:', error)
        this.$message.error('获取单位列表失败')
      } finally {
        this.loading = false
      }
    },

    handleAdd() {
      this.dialogTitle = '添加单位'
      this.editForm = {
        id: undefined,
        province: '',
        city: '',
        district: '',
        unitName: '',
        department: '',
        unitLogo: '',
        configValue: ''
      }
      this.editCityOptions = []
      this.editDistrictOptions = []
      this.dialogVisible = true
    },

    // 处理编辑按钮点击事件
    handleEdit(row) {
      this.dialogTitle = '编辑单位'
      // 初始化编辑表单数据
      this.editForm = {
        id: row.id,
        province: row.provinceName,
        city: row.cityName,
        district: row.districtName,
        unitName: row.unitName,
        department: row.department,
        unitLogo: row.unitLogo,
        configValue: row.configValue
      }

      // 加载相应的省市县选项
      this.loadEditProvinceOptions().then(() => {
        this.handleEditProvinceChange(row.provinceName, true).then(() => {
          this.handleEditCityChange(row.cityName, true)
        })
      })

      this.dialogVisible = true
    },

    // 加载编辑表单的省份选项
    async loadEditProvinceOptions() {
      try {
        const response = await list({}) // 获取所有地区信息
        const regions = response.data

        // 提取唯一省份列表，使用ID和名称
        this.provinceOptions = [...new Map(regions.map(item => [item.provinceId, {
          id: item.provinceId,
          name: item.provinceName
        }])).values()]
      } catch (error) {
        console.error('获取省份列表失败:', error)
        this.$message.error('获取省份列表失败')
      }
    },

    // 省份选择变化时 - 编辑表单
    async handleEditProvinceChange(selectedProvinceName, isInit = false) {
      // 重置城市和区县选择
      if (!isInit) {
        this.editForm.city = ''
        this.editForm.district = ''
      }
      this.editCityOptions = []
      this.editDistrictOptions = []

      if (!selectedProvinceName) return

      try {
        // 根据选中的省份名称获取对应ID
        const selectedProvince = this.provinceOptions.find(p => p.name === selectedProvinceName)
        if (!selectedProvince) return

        // 根据选中的省份ID获取城市列表
        const response = await list({provinceId: selectedProvince.id})
        const regions = response.data

        // 提取唯一城市列表，使用ID和名称
        this.editCityOptions = [...new Map(regions.map(item => [item.cityId, {
          id: item.cityId,
          name: item.cityName
        }])).values()]
      } catch (error) {
        console.error('获取城市列表失败:', error)
        this.$message.error('获取城市列表失败')
      }
    },

    // 城市选择变化时 - 编辑表单
    async handleEditCityChange(selectedCityName, isInit = false) {
      // 重置区县选择
      if (!isInit) {
        this.editForm.district = ''
      }
      this.editDistrictOptions = []

      if (!selectedCityName) return

      try {
        // 根据选中的城市名称获取对应ID
        const selectedCity = this.editCityOptions.find(c => c.name === selectedCityName)
        if (!selectedCity) return

        // 根据选中的城市ID获取区县列表
        const selectedProvince = this.provinceOptions.find(p => p.name === this.editForm.province)
        if (!selectedProvince) return

        const response = await list({
          provinceId: selectedProvince.id,
          cityId: selectedCity.id
        })
        const regions = response.data

        // 提取区县列表，使用ID和名称
        this.editDistrictOptions = [...new Map(regions.map(item => [item.districtId, {
          id: item.districtId,
          name: item.districtName
        }])).values()]
      } catch (error) {
        console.error('获取区县列表失败:', error)
        this.$message.error('获取区县列表失败')
      }
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确认删除该单位吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await deleteRegulatorUnit(row.id)
          this.$message.success('删除成功')
          this.loadUnitList()
        } catch (error) {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    // 根据省名称获取省ID
    getProvinceIdByName(provinceName) {
      const province = this.provinceOptions.find(p => p.name === provinceName)
      return province ? province.id : null
    },

    // 根据市名称获取市ID
    getCityIdByName(cityName) {
      const city = this.editCityOptions.find(c => c.name === cityName)
      return city ? city.id : null
    },

    // 根据区县名称获取区县ID
    getDistrictIdByName(districtName) {
      const district = this.editDistrictOptions.find(d => d.name === districtName)
      return district ? district.id : null
    },

    // 提交表单
    submitForm() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          try {
            // 构造符合后端要求的数据格式
            const submitData = {
              id: this.editForm.id,
              unitName: this.editForm.unitName,
              department: this.editForm.department,
              unitLogo: this.editForm.unitLogo,
              configValue: this.editForm.configValue,
              provinceId: this.getProvinceIdByName(this.editForm.province),
              cityId: this.getCityIdByName(this.editForm.city),
              districtId: this.getDistrictIdByName(this.editForm.district)
            }

            if (this.editForm.id) {
              // 更新操作
              await updateRegulatorUnit(submitData)
              this.$message.success('更新成功')
            } else {
              // 新增操作
              await addRegulatorUnit(submitData)
              this.$message.success('新增成功')
            }
            this.dialogVisible = false
            this.loadUnitList()
          } catch (error) {
            console.error('保存失败:', error)
            this.$message.error('保存失败')
          }
        }
      })
    },

    handleDialogClose() {
      this.$refs.editForm.resetFields()
    },

    handleSelectionChange() {
    },

    getConfigDescription(configValue) {
      const configMap = {
        '0': '标题',
        '1': 'LOGO',
        '2': '打印',
        '3': '首页',
        '4': '四川省追溯平台',
        '5': '大屏权限',
        '6': '合格证抬头'
      }
      return configMap[configValue] || ''
    }
  }
}
</script>

<style scoped>
.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}
</style>
